package org.ehe.business.step.converter;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author :zhangnn
 * @className :MultipartFileToFileConverter
 * @description: TODO
 * @date 2025-08-05 15:54:10
 */
public class MultipartFileToFileConverter {
    /**
     * 将MultipartFile转换为File
     * @param multipartFile 上传的文件
     * @return 转换后的File对象
     * @throws Exception 转换过程中的异常
     */
    public static File convert(MultipartFile multipartFile) throws Exception {
        // 创建临时文件
        File tempFile = File.createTempFile("temp", multipartFile.getOriginalFilename());

        // 将MultipartFile的内容写入临时文件
        try (InputStream in = multipartFile.getInputStream();
             OutputStream out = new FileOutputStream(tempFile)) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }

        // 当JVM退出时删除临时文件（可选，根据需求决定）
        tempFile.deleteOnExit();

        return tempFile;
    }
}
